import express from "express";

import { validate, validators } from "../validate.js";
import { auth } from "../auth.js";
// 导入数据库连接
import { db } from "../db/index.js";
// 定义子路由
const router = express.Router();
// 使用认证中间件
router.use(auth);
// 使用中间件验证代办信息是否存在
async function isExistsTodo(req, res, next) {
  const { tid } = req.params;
  const userId = req.session.userId;
  // 获取待办事项信息
  const todo =
    await db.findOne`select * from todo where id = ${tid} and user_id = ${userId}`;
  if (!todo) {
    return res.status(404).json({
      success: false,
      message: "待办事项不存在",
    });
  }
  next();
}
// 定义路由
router
  // 获取待办事项
  .get(
    "/todo",
    validate(validators.limit, validators.offset),
    async (req, res) => {
      const { limit = 10, offset = 0 } = req.query;
      const userId = req.session.userId;
      const todos = await db.findMany`
    select * from todo where user_id = ${userId} limit ${limit} offset ${offset}
    `;
      const { count } = await db.findOne`
    select count(*) as count from todo where user_id = ${userId}
    `;
      res.json({
        success: true,
        query: { count, limit, offset, results: todos },
      });
    }
  )
  // 新建待办事项
  .post(
    "/todo",
    validate(validators.title, validators.description, validators.priority),
    async (req, res) => {
      const { title, description, priority } = req.body;
      const userId = req.session.userId;
      const todo = await db.insert`
    insert into todo (title, description, priority, user_id) values (${title}, ${description}, ${priority}, ${userId})
    `;
      res.json({
        success: true,
        message: "创建待办事项成功",
        object: todo,
      });
    }
  )
  .put(
    "/todo/:tid",
    validate(
      validators.todoId,
      validators.title,
      validators.description,
      validators.priority
    ),
    isExistsTodo,
    async (req, res) => {
      // 获取待办事项信息
      const { tid } = req.params;
      const { title, description, priority } = req.body;
      const userId = req.session.userId;
      // 更新用户代办信息
      await db.update`update todo set title = ${title}, description = ${description}, priority = ${priority} where id = ${tid} and user_id = ${userId}`;
      // 获取更新后的代办信息
      const todo =
        await db.findOne`select * from todo where id = ${tid} and user_id = ${userId}`;
      res.json({
        success: true,
        message: "更新待办事项成功",
        object: todo,
      });
    }
  )
  .delete(
    "/todo/:tid",
    validate(validators.todoId),
    isExistsTodo,
    async (req, res) => {
      const { tid } = req.params;
      const userId = req.session.userId;

      // 删除用户代办信息
      await db.delete`delete from todo where id = ${tid} and user_id = ${userId}`;
      //
      res.json({
        success: true,
        message: "删除待办事项成功",
      });
    }
  )
  .put(
    "/todo/:tid/done",
    validate(validators.todoId),
    isExistsTodo,
    async (req, res) => {
      const { tid } = req.params;
      const userId = req.session.userId;
      await db.update`update todo set finished_at = current_timestamp where id = ${tid} and user_id = ${userId}`;
      const todo =
        await db.findOne`select * from todo where id = ${tid} and user_id = ${userId}`;
      res.json({
        success: true,
        message: "更新待办事项成功",
        object: todo,
      });
    }
  );

export default router;
